import { setJson, setJsonAll, getJson, getJsonAll, setConfig } from './readFile.js'

/**
 * 获取card状态
 * @param {string} card 卡密
 * @returns {number?} 天数
 */
function getCard(card) {
    return getJson(card, 'card')
}

/**
 * 增加或减少card天数
 * @param {string} card 卡密
 * @param {number} day 剩余天数
 * @param {'add'|'del'} type 类型 添加或减少
 * @returns {boolean} 是否修改成功
 */
function setCardDay(card, day, type = 'add') {
    const data = getJson(card, 'card')
    if (data) {
        if (type === 'add') {
            data.day += day
        } else if (type === 'del') {
            data.day -= day
        }
        setJson(card, 'card', data, 'modify')
        return true
    }
    return false
}

/**
 * 增加指定数量的card
 * @param {number} day 天数
 * @param {number} count 数量 
 */
function addCard(day, count = 1) {
    const data = getJsonAll()
    for (let i = 0; i < count; i++) {
        const card = generateRandomString(10)
        data[card] = {
            card,
            status: 0,
            day,
        }
    }
    setJsonAll(data)
}

/**
 * 删除card
 * @param {*} card 
 */
function delCard(card) {
    const data = getJsonAll()
    const group = data.card[card]?.group
    if (group) {
        delete data.group[group]
    }
    delete data.card[card]
    setJsonAll()
}

/**
 * 获得所有的card数据
 * @returns {{card:string,day:number,status:0|1,group_id:string?}>}
 */
function getAllCard() {
    return Object.values(getJsonAll().card)
}

/**
 * 获取群号对应的card
 * @param {number|string} group_id 
 */
function getGroupCard(group_id) {
    return getJson(group_id, 'group')
}

/**
 * 修改card对应的群号
 * @param {string} card
 * @param {string|number} group_id
 * @param {'add'|'del'} type
 */
function setGroupCard(card, group_id, type = 'add') {
    const data = getJson(card, 'card')
    const oldGroup = data.group_id
    if (data) {
        if (type === 'add') {
            data.group_id = group_id
            data.status = 1
            setJson(group_id, 'group', { card, group_id }, 'add')
            setConfig(group_id, 'whiteGroup', 'add')
        } else if (type === 'del') {
            data.status = 0
            delete data.group_id
            setConfig(group_id, 'whiteGroup', 'del')
        }
        if (oldGroup) {
            setJson(oldGroup, 'group', null, 'del')
            setConfig(oldGroup, 'whiteGroup', 'del')
        }
        setJson(card, 'card', data, 'modify')
        return true
    }
    return false
}


/**
 * 生成指定长度的随机数
 * @param {number} length 长度
 * @returns 
 */
function generateRandomString(length) {
    let chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    let result = '';
    for (let i = 0; i < length; i++) {
        result += chars[Math.floor(Math.random() * chars.length)];
    }
    return result;
}

export {
    getCard,
    setCardDay,
    addCard,
    delCard,
    getAllCard,
    getGroupCard,
    setGroupCard,
    generateRandomString
}